import { Base_model } from '../../util/base_model.js';

class Cart_model extends Base_model
{
  constructor() {
    super();

    this._storageKey = 'cart';
  }

  getCarts() {
    var cartList = wx.getStorageSync(this._storageKey);
    
    if (! cartList) {
      return [];
    }

    return cartList;
  }

  /**
   * 获取购物车总的数量
   * flag 表示商品是否选择
   * totalCount 购物车的商品数量总和
   * productCount 商品数量
   */
  getCartCount(flag) {
    var cartList = this.getCarts()
    var totalCount = 0,
      productCount = 0;   
    
    if (cartList) {
      var length = cartList.length;
      for (var i = 0; i < length; i++) {
        if (flag) {
          if (cartList[i].selectStatus) {
            totalCount += cartList[i].counts;
            productCount++;
          }
        } else {
          totalCount += cartList[i].count;
          productCount++;
        }
      }
    }

    return {
      totalCount:totalCount,
      productCount:productCount
    }
  }

  add(data, productCount) {
    var cartData = this.getCarts();
    var product = this.hasProduct(data.id, cartData);

    if (product.index != -1) {
      cartData[product.index].counts += productCount;
    } else {
      data.counts = productCount;
      data.selectStatus = true;
      cartData.push(data);
    }

    wx.setStorageSync(this._storageKey, cartData);

    return cartData;
  }

  _changeCount(id, count) {
    var cartData = this.getCarts();
    var product = this.hasProduct(id, cartData);
    
    if (product.index != -1) {
      cartData[product.index].counts += count;
    }

    wx.setStorageSync(this._storageKey, cartData);
    
    return true;
  }

  addCount(id) {
    this._changeCount(id, 1);
  }

  cutCount(id) {
    this._changeCount(id, -1);
  }


  hasProduct(id, cartData) {
    var product = {index:-1};
    for (var key in cartData) {
      if (cartData[key].id == id) {
        product = {
          index:key,
          data:cartData[key]
        }
      }
    }

    return product;
  }

  delete(id) {
    var cartList = this.getCarts();
    for (var key in cartList) {
      if (cartList[key].id == id) {
        cartList.splice(key, 1);
      }
    }

    wx.setStorageSync(this._storageKey, cartList);
  }
}

export { Cart_model }